<?php

namespace app\logic\common;

class L_appStore
{
    /**
     * 获取插件ID
     */
    public function getPluginId(){
        $auth_plugin=data("cms.auth.plugin_data",array());
        $plugin_ids=array();
        if($auth_plugin){
            foreach($auth_plugin as $val){
                if($this->checkDate($val)){
                    $plugin_ids[]=$val["pluginId"];
                }
            }
        }
        return array_filter(array_unique($plugin_ids));
    }

    /**
     * 检测日期
     * @param $data
     */
    public static function checkDate($data){
        $nowTime=time();
        if($data["isPermanent"]=="1"){
            return true;
        }else if($data["expireMin"] <=  $nowTime && $data["expireMax"] > $nowTime){
            return true;
        }
        return false;
    }

    /**
     * 使用激活码
     * @param string $paramObj
     */
    public function usedByCardName($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'token' => 'require',
                'cardName' => 'require',
                'extendData' => '',
                'cardPwd' => '',
                'seller_id' => '',
            );
            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $data = array();
            $data["cardName"] = $dataObj->request->cardName;
            $data["extendData"] = $dataObj->request->extendData;
            $data["cardPwd"] = $dataObj->request->cardPwd;
            $data["token"] = $dataObj->request->token;
            $data["seller_id"] = $dataObj->request->seller_id;
            $headers = array(
                "Authorization:Bearer {$dataObj->request->token}",
            );
            $headers = array_merge($headers, getSignV1($data));
            $submitUrl = config("app.cmsSiteUrl")."/api/yifang_shop/prop/use";
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "submitUrl" => $submitUrl,
                "method" => "put",
                "time" => 10,
                "data" => $data,
                "headers" => $headers,
            );
            $checkResult = app("P_http")->send($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $result = $checkResult["result"];
                $body = toJsonDecode($result["body"]);
                if ($body) {
                    if ($body["success"]) {
                        $final_arr["result"] = $body["data"];
                    } else {
                        $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, $body["code"], $body["codeMsg"]);
                    }
                } else {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"), $result["error_msg"]);
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        return $final_arr;
    }

    /**
     * 下载文件
     * @param string $paramObj
     */
    public function downloadFile($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'downUrl' => 'require',
                'pluginId' => 'require',
                'num' => '',
                'fileSize' => '',
            );
            $dataDefault = array();
            $dataDefault["num"]=0;
            $dataDefault["fileSize"]=0;
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $plugin_ids=$this->getPluginId();
            if(!in_array($dataObj->request->pluginId,$plugin_ids)){
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"));
            }
        }
        if ($final_arr["error_no"] == 0) {
            $downUrl=$dataObj->request->downUrl;
            if (strpos($downUrl, ".") === false) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"));
            } else {
                $filePath = str_replace("\\", "/", runtimePath("cache/download/plugin"));
                makeDir($filePath);
                $parts = explode(".", $downUrl);
                $extension = end($parts);
                $filename = $filePath . $dataObj->request->pluginId . '.' . $extension;
                if ($dataObj->request->num == "0") {
                    //删除文件
                    if (is_file($filename)) {
                        unlink($filename);
                    }
                }
                $fileResult = app("yifangDownload")->downloadUrl($downUrl,$dataObj->request->num,$dataObj->request->fileSize);
                if (isset($fileResult["content"])) {
                    if($fileResult["content"]){
                        file_put_contents($filename, base64_decode($fileResult["content"]), FILE_APPEND);
                    }
                    unset($fileResult["content"]);
                }
                $final_arr["result"] = $fileResult;
            }
        }
        return $final_arr;
    }

    /**
     * 安装[执行]
     * @param string $paramObj
     */
    public function install($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'pluginId' => 'require',
                'goodId' => '',
            );
            $dataDefault = array();
            $dataDefault["goodId"]=0;
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $plugin_ids=$this->getPluginId();
            if(!in_array($dataObj->request->pluginId,$plugin_ids)){
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"));
            }
        }
        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->pluginId,
            );
            $checkResult = app("L_Api_goods")->info($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $result = $checkResult["result"];
                if ($final_arr["error_no"] == 0) {
                    $parts = explode(".", $result["downUrl"]);
                    $extension = end($parts);

                    $filePath = str_replace("\\", "/", runtimePath("cache/download/plugin"));
                    makeDir($filePath);
                    $filename = $filePath . $result['id'] . '.' . $extension;
                    //自动解压文件
                    $pluginDir = YIFANG_ROOT . "/plugins/" . $result["pluginDir"];
                    if (is_file($filename)) {
                        if (env()->get("APP_debug") == 1) {
                            $ok = true; //调试模式跳过备份解压
                        } else {
                            if (is_dir($pluginDir)) {
                                //备份
                                $filePath = str_replace("\\", "/", runtimePath("cache/backups/plugin"));
                                makeDir($filePath);
                                $rand = rand(1111, 9999);
                                $date = app("yifangTime")::getDateTime('YmdHis') . $rand;
                                $backupFilename = $filePath . $result["pluginDir"] . $date;
                                dirCopy2($pluginDir, $backupFilename);
                            }
                            $ok=app("yifangZip")->unzip2($filename,$pluginDir);
                        }
                        if (!$ok) {
                            $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"));
                        } else {
                            //把详细信息推入文件夹内
                            if($dataObj->request->goodId){
                                $result["goodId"]=$dataObj->request->goodId;
                                file_put_contents($pluginDir . "/info.json", json_encode($result, JSON_PRETTY_PRINT));
                            }else{
                                file_put_contents($pluginDir . "/load", "");
                            }
                        }
                    }
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        return $final_arr;
    }

    /**
     * 插件安装[执行]
     * @param string $paramObj
     */
    public function pluginInstall($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'pluginDir' => 'require',
            );
            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $pluginDir = $dataObj->request->pluginDir;
            $namespace = "\\plugins\\{$pluginDir}\\config";
            if (class_exists($namespace)) {
                $pluginObj = new $namespace;
                if(method_exists($pluginObj,"install")){
                    $checkResult = $pluginObj->install();
                    if ($checkResult["error_no"] == "0") {

                    } else {
                        $final_arr = logCallErrorMsg($final_arr, $checkResult);
                    }
                }
            } else {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_NOTICE, app("errorCode")::OP_FAIL,lang("sys.opFail"));
            }
        }
        return $final_arr;
    }

    /**
     * 卸载[执行]
     * @param string $paramObj
     */
    public function uninstall($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'pluginDir' => 'require',
            );
            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            //先通知插件我要卸载了
            $pluginDir = $dataObj->request->pluginDir;
            $namespace = "\\plugins\\{$pluginDir}\\config";
            if (class_exists($namespace)) {
                $pluginObj = new $namespace();
                // 开启输出缓冲区
                ob_start();
                $pluginObj->uninstall();//仅通知,没有返回信息
                $output = ob_get_clean(); //拦截插件的输出信息

                $pluginDir = YIFANG_ROOT . "/plugins/" . $pluginDir;
                //开始删除目录
                dirDelete($pluginDir);
                //开始删除插件的数据库内功能记录
                $tempObj = getParamsObj(null, ["plugins" => "plugins/" . $dataObj->request->pluginDir]);
                $checkResult = app("S_Admin_adminFunc")->deletePlugins($tempObj);
                if ($checkResult["error_no"] == 0) {
                    //开始删除插件的数据库内菜单记录
                    $tempObj = getParamsObj(null, ["plugin" => "plugins/" . $dataObj->request->pluginDir]);
                    $checkResult = app("S_Admin_adminMenu")->deletePlugins($tempObj);
                    if ($checkResult["error_no"] == 0) {
                        app("L_Common_plugins")->deletePluginsCache(); //删除已安装插件缓存,
                    } else {
                        $final_arr = logCallErrorMsg($final_arr, $checkResult);
                    }
                } else {
                    $final_arr = logCallErrorMsg($final_arr, $checkResult);
                }
            } else {
                app("L_Common_plugins")->deletePluginsCache(); //删除已安装插件缓存, 估计判断问题,也删除缓存
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_NOTICE, app("errorCode")::VERIFY_DATA_FAIL, "插件未安装");
            }
        }
        return $final_arr;
    }

    /**
     * 设置视图
     * @param string $paramObj
     */
    public function setUpView($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'pluginDir' => 'require',
            );
            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            //调用插件设置视图
            $namespace = "plugins/".$dataObj->request->pluginDir . "/config";
            $namespace = str_replace("/", "\\", $namespace);
            if (class_exists($namespace)) {
                $pluginObj = new $namespace();
                if (method_exists($pluginObj, "setUpView")) {
                    $final_arr["result"] = $pluginObj->setUpView();
                } else {
                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_NOTICE, app("errorCode")::VERIFY_DATA_FAIL, "该插件无设置页面");
                }
            } else {
                app("L_Common_plugins")->deletePluginsCache(); //删除已安装插件缓存, 估计判断问题,也删除缓存
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_NOTICE, app("errorCode")::VERIFY_DATA_FAIL, "插件未安装");
            }
        }
        return $final_arr;
    }

    public function __call($name, $arguments)
    {
        return recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::UNDEFINED_METHOD, lang("sys.noMethodDefined"), $name, $arguments);
    }
}